package net.palla.biblio.client;

import net.palla.biblio.shared.Cdd;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class CddDetailPanel extends DialogBox {

	private BiblioServiceAsync service;
	private Cdd parent;
	
	private static CddDetailPanelUiBinder uiBinder = GWT
			.create(CddDetailPanelUiBinder.class);

	interface CddDetailPanelUiBinder extends UiBinder<Widget, CddDetailPanel> {
	}

	@UiField Label lParent;
	@UiField TextBox tbCdd1;
	@UiField TextBox tbCdd2;
	@UiField TextBox tbName;
	@UiField Button btnSave;
	@UiField Button btnCancel;

	public CddDetailPanel(BiblioServiceAsync service, Cdd parent) {
		//initWidget(uiBinder.createAndBindUi(this));
		this.add(uiBinder.createAndBindUi(this));
		this.service = service;
		this.parent = parent;
		if (parent != null)
			lParent.setText(parent.getCdd1() + " " + parent.getCdd2() + " " + parent.getName());
		else
			lParent.setText("No parent selected");
	}

	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		Cdd cdd = new Cdd();
		cdd.setCdd1(tbCdd1.getText());
		cdd.setCdd2(tbCdd2.getText());
		cdd.setName(tbName.getText());
		if (parent == null)
			cdd.setParent(null);
		else
			cdd.setParent(parent.getId());
		try {
			service.saveCdd(cdd, new AsyncCallback<Cdd>() {
				
				@Override
				public void onSuccess(Cdd result) {
					hide();
				}
				
				@Override
				public void onFailure(Throwable caught) {
					Window.alert(caught.getMessage());					
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		this.hide();
	}	
	
}
